<template>
  <div class="main-menu">
    <p style="font-family: KAITI;text-align: left;font-size: 30px;font-weight: 400">菜单编辑    <span
      style="float: right;font-size: 14px;padding-top: 10px;"><span @click="gotoMain()" style="cursor: pointer">{{'<<'}}返回主页面&nbsp;&nbsp;</span> <span
      style="cursor: pointer" @click="loginout()">退出</span></span>
    </p>
    <div style="height: 40px;text-align: left;">
      <el-button size="small" type="primary" @click="addMenu({id:'0'})">添加一级菜单</el-button>
    </div>
    <div style="font-size: 0px">

      <div class="block">
        <el-tree
          :data="data5"
          ref="tree"
          node-key="id"
          :default-expand-all="true"
          :default-checked-keys="defaultKey"
          :expand-on-click-node="false"
        >
      <span class="custom-tree-node" slot-scope="{ node, data }">
          <div class="menu-label">{{ node.label }}</div>
        <div class="menu-button">
          <el-button
            type="text"
            size="mini"
            @click="toAddMenu(data)" v-show="data.fid=='0'" style="margin-left: 5px;">
            <i class="el-icon-circle-plus"></i>
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="remove(node, data)" v-show="data.fid=='0'" style="margin-left: 5px;">
            <i class="el-icon-remove"></i>
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="remove(node, data)" v-show="data.fid!='0'" style="margin-left: 28px;">
            <i class="el-icon-remove"></i>
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="update(node, data)" style="margin-left: 5px;">
            <i class="el-icon-edit"></i>
          </el-button>

          <!--</span>-->
        </div>
      </span>
        </el-tree>
        <el-dialog
          :title="showName"
          :visible.sync="dialogVisible"
          width="30%"
          :before-close="handleClose">
          <div style="width: 100%;">
            <div style="width:100px;height:40px;line-height:40px;">
              菜单名称：
            </div>
            <div style="margin-left:100px;margin-top:-40px;width:auto;">
              <el-input v-model="menuName1" auto-complete="off" style="height: 40px;"></el-input>
            </div>
          </div>
          <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="addMenu1(addData)">确 定</el-button>
  </span>
        </el-dialog>
      </div>
      <div class="right-menu">
        <div style="padding-bottom: 20px;" v-show="isEdit">
          <div style="width:100px;height:40px;line-height:40px;font-size: 14px;">
            菜单名称：
          </div>
          <div style="margin-left:100px;margin-top:-40px;width:auto;">
            <el-input v-model="menuName" auto-complete="off" style="height: 40px;"></el-input>
          </div>

        </div>
        <div style="position: relative" v-show="isEdit">
        <div v-show="isEdit">
          <!--<quill-editor class="edit-menu" ref="myTextEditor"-->
                        <!--:content="content"-->
                        <!--@change="onEditorChange($event)">-->
          <!--</quill-editor>-->
          <div id="editor-container1">
          </div>
        </div>
          <span class="new-image">
            <button @click="toAddNewImage" class="button-back">
              <i class="el-icon-picture-outline"></i>
            </button>
          </span>
        </div>
        <div style="margin-top: 100px;" v-show="isEdit">
          <el-button type="primary" @click="toSaveMenu(addData)">保 存</el-button>
        </div>
      </div>
    </div>

    <el-dialog :visible.sync="showImageDialog" width="1000px" top="5vh" center @close="deleteImage()">
      <div style="width:900px;margin: 0 auto;text-align: center">
        <div style="width: 700px;display: inline-block;vertical-align: top;border: 1px solid #efefef">
        <canvas id="canvasDefault" width="700px" height="700px"></canvas>
        </div>
        <div style="display: inline-block;vertical-align: top;text-align: left;width:150px">
          <div>图片大小</div>
          <div>宽度：{{widthDefault}}px</div>
          <div>高度：{{heightDefault}}px</div>
        </div>
        <el-button type="primary" @click="addNewImage()" style="margin-top: 20px">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    quillEditor
  } from 'vue-quill-editor';

  export default {
    name: 'menu-index',
    data() {
      return {
        data5: [],
        menu: [],
        dialogVisible: false,
        menuName: '',
        addData: [],
        showName: "添加菜单",
        content: '',
        isEdit: false,
        defaultKey: [],
        isUp: false,
        menuName1: '',
        quill:null,
        showImageDialog:false,
        canvas:null,
        imgInstance:null,
        imgSrc:'',
        widthDefault:'',
        heightDefault:'',
        offIndex:0,

      }
    },

    methods: {
      getIndexLength(){
        let vm=this;
          vm.offIndex=vm.quill.getSelection().index;
      },
      addNewImage(){
        let vm=this;
        vm.canvas.getActiveObject().set("left","0");
        vm.canvas.getActiveObject().set("top","0");
        vm.canvas.requestRenderAll();
        setTimeout(function () {
        let url=vm.canvas.toDataURL({
          format: 'png',
          quality: 1,
          width:vm.widthDefault,
          height:vm.heightDefault,
        });
        vm.quill.insertEmbed(vm.offIndex,'image',url);
        vm.showImageDialog=false;
        },20);
      },
      initCanvas(){
        let vm=this;
        setTimeout(function () {
          vm.canvas = new fabric.Canvas('canvasDefault');
        },100)
      },
      deleteImage(){
        let vm=this;
        vm.canvas.remove(vm.imgInstance);
      },
      toAddNewImage(){
        /*内存创建input file*/
        this.quill.focus();
        if(this.quill.getSelection()==null){
          this.$message({
            message: "请设置插入图片的位置！",
            type: 'warning'
          });
          return;
        }else{
          this.offIndex=this.quill.getSelection().index;
        }
        let input = document.createElement('input');
        input.type = 'file';
        input.name = this.fileName;
        input.accept = 'image/jpeg,image/png,image/jpg,image/gif';
        input.onchange = this.onFileChange;
        input.click()
      },
      onFileChange(e) {
        let vm = this;
        let file = e.target.files[0];
        let img = new Image();
        let reader = new FileReader();
        reader.onload = function (e1) {
          if(vm.canvas==null){
            vm.initCanvas();
          }
          vm.showImageDialog=true;
          img.src = e1.target.result;
          vm.imgSrc=img.src;
          img.onload = function () {
            setTimeout(function () {
              vm.imgInstance = new fabric.Image(img, {
                left:20,
                top:20,
                width: img.width,
                height: img.height,
              });
              vm.widthDefault=img.width;
              vm.heightDefault=img.height;
              vm.canvas.add(vm.imgInstance);
              vm.canvas.setActiveObject(vm.imgInstance);
              vm.canvas.getActiveObject().setControlVisible("mtr",false);
              vm.canvas.requestRenderAll();
              vm.imgInstance.on('scaling', function() {
                let width=vm.canvas.getActiveObject().getWidth();
                let height=vm.canvas.getActiveObject().getHeight();
                let zroomX=vm.canvas.getActiveObject().get("scaleX");
                let zroomY=vm.canvas.getActiveObject().get("scaleY");
                vm.widthDefault=Math.floor(width*zroomX);
                vm.heightDefault=Math.floor(height*zroomY);
              });
            },500);
          }
        };
        reader.readAsDataURL(file);
      },


      loginout() {
        this.$axios.HttpGet({url: "/api/logout"}, {})
          .then((data) => {
            if (data.data[0].success == '1') {
              sessionStorage.setItem("user","");
              this.router.push({path: 'login'});
            }
          }).catch((error) => {
        });
      },
      gotoMain() {
        this.router.push({path: 'main'});
      },
      onEditorChange({editor, html, text}) {//富文本编辑
        this.content = html;
      },
      getMenu(menu) {
        this.$axios.HttpGet({url: "/api/cross/getMenuById"}, {id: menu.id})
          .then((data) => {
            this.menuName = data.data[0].menu.v_name;
            this.content = data.data[0].menu.content;
            this.quill.container.firstChild.innerHTML=data.data[0].menu.content;
          }).catch((error) => {
        })
      },

      toSave(menu) {
        if (this.menuName1 == "") {
          this.$message({
            message: "菜单名称不能为空！",
            type: 'warning'
          });
          return;
        }
        if (this.menuName1.length > 10) {
          this.$message({
            message: '菜单名称请控制在10个字符之内！',
            type: 'warning'
          });
          return;
        }
        this.$axios.HttpPost({url: "/api/auth/addMenu"}, {fid: menu.id, name: this.menuName1})
          .then((data) => {
            this.dialogVisible = false;
            this.data5.push({id: data.data[0].res, label: this.menuName1, children: [], fid: menu.id})
            this.menuName1 = '';
            this.$message({
              message: '添加成功！',
              type: 'success'
            });
          }).catch((err) => {
        })
      },

      toUpdate(menu) {
        if (this.menuName1 == "") {
          this.$message({
            message: "菜单名称不能为空！",
            type: 'warning'
          });
          return;
        }

        if (this.menuName1.length > 10) {
          this.$message({
            message: '菜单名称请控制在10个字之内！',
            type: 'warning'
          });
          return;
        }
        this.$axios.HttpGet({url: "/api/auth/updateMenuName"}, {id: menu.id, name: this.menuName1})
          .then((data) => {
            this.dialogVisible = false;
            this.addData.label = this.menuName1;
            this.menuName1 = '';
            this.$message({
              message: '修改成功！！',
              type: 'success'
            });
          }).catch((err) => {
          console.log(err);
        })
      },
      addMenu1(menu) {
        if (this.showName === "添加菜单") {
          this.toSave(menu);
        } else if (this.showName === '修改菜单') {
          this.toUpdate(menu);
        }
      },

      addMenu(data) {
        this.isEdit = false;
        this.showName = "添加菜单";
        this.dialogVisible = true;
        this.addData = data;
      },
      toAddMenu(data) {
        this.isUp = false;
        this.addData = data;
        this.menuName = '';
        this.content = "";
        this.quill.container.firstChild.innerHTML='';
        this.isEdit = true;
      },
      toSaveMenu(menu) {
        this.content=this.quill.container.firstChild.innerHTML;
        if (this.menuName === '') {
          this.$message({
            message: '菜单名称不能为空！',
            type: 'warning'
          });
          return;
        }
        ;
        if (this.menuName.length > 10) {
          this.$message({
            message: '菜单名称请控制在10个字之内！',
            type: 'warning'
          });
          return;
        }
        ;
        if (this.content === '') {
          this.$message({
            message: '文档内容不能为空！',
            type: 'warning'
          });
          return;
        }
        ;
        if (this.isUp) {
          this.$axios.HttpPost({url: "/api/auth/updateMenuChild"}, {id: menu.id, name: this.menuName, content: this.content})
            .then((data) => {
              this.addData.label = this.menuName;
              this.$message({
                message: '更新成功！',
                type: 'success'
              });
            }).catch((err) => {
            console.log(err);
          })
        } else {
          this.$axios.HttpPost({url: "/api/auth/addMenu"}, {fid: menu.id, name: this.menuName, content: this.content})
            .then((data) => {
              this.content = '';
              this.quill.container.firstChild.innerHTML='';
              const newChild = {id: data.data[0].res, label: this.menuName, children: [], fid: menu.id};
              if (!this.addData.children) {
                this.$set(this.addData, 'children', []);
              }
              this.addData.children.push(newChild);
              this.menuName = '';
              this.$message({
                message: '添加成功',
                type: 'success'
              });
            }).catch((err) => {
            console.log(err);
          })
        }

      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
            this.menuName1 = '';
          })
          .catch(_ => {
          });
      },
      remove(node, menu) {
        this.isEdit = false;
        this.$axios.HttpGet({url: "/api/auth/deleteMenu"}, {id: menu.id, isFid: menu.fid})
          .then((data) => {
            this.dialogVisible = false;
            const parent = node.parent;
            const children = parent.data.children || parent.data;
            const index = children.findIndex(d => d.id === menu.id);
            children.splice(index, 1);
          }).catch((err) => {
          console.log(err);
        });


      },
      update(node, data) {
        this.addData = data;
        if (data.fid == '0') {
          this.showName = "修改菜单";
          this.dialogVisible = true;
        } else {
          this.isUp = true;
          this.content = "";
          this.quill.container.firstChild.innerHTML='';
          this.isEdit = true;
          this.getMenu(data);
        }

      },

    },
    mounted: function () {
      var Font = Quill.import('formats/font');
// We do not add Aref Ruqaa since it is the default
      Font.whitelist = ['Arial', '宋体', '黑体', '微软雅黑','楷体','微软正黑体','新宋体','仿宋','标楷体'];
      Quill.register(Font, true);
      this.quill = new Quill('#editor-container1', {
        modules: {
          toolbar: { container:[
            [{
              'font': ['Arial', '宋体', '黑体', '微软雅黑','楷体','微软正黑体','新宋体','仿宋','标楷体']
            }],
            ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
            ['blockquote', 'code-block'],
            ['link', 'image'],
            [{ 'header': 1 }, { 'header': 2 }],               // custom button values
            [{ 'list': 'ordered'}, { 'list': 'bullet' }],
            [{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
            [{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
            [{ 'direction': 'rtl' }],                         // text direction

            [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],

            [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
            [{ 'align': [] }],

            ['clean']



          ],
          },
        },
        theme: 'snow'
      });

      this.$axios.HttpGet({url: "/api/cross/getMenuList"}, {})
        .then((data) => {
          this.menu = data.data[0].list;
          this.content = data.data[0].content.content;
          for (var i = 0; i < this.menu.length; i++) {
            let menu1 = {
              id: this.menu[i][0].id,
              label: this.menu[i][0].v_name,
              children: [],
              fid: this.menu[i][0].v_menu_fid
            };
            if (this.menu[i].length > 0) {
              for (var j = 0; j < this.menu[i][1].length; j++) {
                menu1.children.push({
                  id: this.menu[i][1][j].id,
                  label: this.menu[i][1][j].v_name,
                  fid: this.menu[i][1][j].v_menu_fid
                });
              }
            }
            this.data5.push(menu1);
          }
        }).catch((err) => {
//        console.log(err);
      })
    }
  };
</script>

<style>
  .new-image{
    position: absolute;
    display: inline-block;
    height: 20px;
    width: 20px;
    top: 34px;
    left: 280px;
    cursor: pointer;
  }
  .button-back{
    background-color: white;
    border: 1px solid white;
    padding: 0px;
    margin: 0px;
    outline: none;
    font-size: 20px;
  }
  .el-icon-picture-outline{
    cursor: pointer;
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right-menu: 8px;
  }

  .main-menu {
    margin: 0 auto;
    /*border: 1px solid red;*/
    /*width: 80%;*/
    width: 1250px;
  }

  .block {
    float: left;
    margin: 0;
    /*width:20%;*/
    /*border: 1px solid black;*/
    display: inline-block;
    width: 330px;
    height: 800px;
  }

  .right-menu {
    width: 900px;
    display: inline-block;
    height: 400px;
  }

  .edit-menu {
    height: 500px;
  }

  .menu-button {
    display: inline-block;
    width: 100px;
    text-align: left;
  }

  .menu-label {
    width: 180px;
    display: inline-block;
    text-align: left;
  }
</style>
